package com.wuwei.tran.utils;

import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Base64;


public class FileUtils {

    /**
     * 获取File 对应的icon的base64编码
     * @param file
     * @return
     * @throws IOException
     */
    public static String getFileIconBase64(File file) throws IOException {
        // 获取文件图标
        FileSystemView fileSystemView = FileSystemView.getFileSystemView();
        Icon icon = fileSystemView.getSystemIcon(file);
        BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);

        // 绘制图标到 BufferedImage
        icon.paintIcon(null, image.getGraphics(), 0, 0);

        // 将图标转换为 Base64 字符串
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        javax.imageio.ImageIO.write(image, "png", baos);  // 使用 PNG 格式保存
        byte[] imageBytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);  // 转换为 Base64 编码
    }

    public static String getFileIconBase64(Path path) throws IOException {
        // 将 Path 转换为 File
        File file = path.toFile();

        return getFileIconBase64(file);
    }


}
